package com.objcat.servicea.controller;


import com.alibaba.fastjson.JSONObject;
import com.objcat.servicea.entity.po.PowerPo;
import com.objcat.servicea.entity.po.RolePo;
import com.objcat.servicea.entity.vo.UserVo;
import com.objcat.servicea.service.PowerService;
import com.objcat.servicea.service.RoleService;
import com.objcat.servicea.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author misheep
 * @since 2020-07-27
 */

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PowerService powerService;

    @RequestMapping("index")
    public String index() {
        return "index";
    }

    @RequestMapping("login")
    @ResponseBody
    public Object login(@RequestBody String file, HttpServletResponse response) {
        log.info("正常进入user/login");
        JSONObject jsonObject = (JSONObject) JSONObject.parse(file);
        String userName = jsonObject.getString("username");
        String userPassword = jsonObject.getString("password");
        UserVo userVo = userService.getUser(userName, userPassword);
        if(userVo==null){
            return null;
        }
        //获得角色
        RolePo rolePo = roleService.getRole(userVo);
        //获得权限
        List<PowerPo> powerPoList = powerService.getPower(rolePo);
        //添加进header
        JSONObject userInfo = new JSONObject();
        userInfo.put("userId", userVo.getUserId());
        userInfo.put("username", userVo.getUserName());
        List<String> powers = new ArrayList<>();
        powerPoList.forEach(powerPo -> {
            powers.add(powerPo.getPowerName());
        });
//        powers.add("Admin");
//        powers.add("Dev");

        userInfo.put("powers", powers);
        response.addHeader("AccountInfo", userInfo.toJSONString());
        JSONObject result = new JSONObject();
        result.put("code", 0);
        return result;
    }

}
